package binarytree;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/24 12:17
 * https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/
 *  二叉搜索树中的插入操作
 */
public class InsertIntoBST {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 递归方法
     * @param root
     * @param val
     * @return
     */
    public static TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            root = new TreeNode(val);
            return root;
        }
        if (root.val > val) {
            root.left = insertIntoBST(root.left, val);
        } else {
            root.right = insertIntoBST(root.right, val);
        }
        return root;
    }


    /**
     * 迭代法
     * @param root
     * @param val
     * @return
     */
    public static TreeNode insertIntoBST1(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }
        TreeNode cur = root;
        TreeNode pre = cur;
        while (cur != null) {
            pre = cur;
            if (cur.val > val) {
                cur = cur.left;
            } else {
                cur = cur.right;
            }
        }
        TreeNode node = new TreeNode(val);
        if (pre.val > val) {
            pre.left = node;
        } else {
            pre.right = node;
        }
        return root;
    }


    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.right = new TreeNode(7);
        TreeNode treeNode = insertIntoBST(root, 5);
        System.out.println();
    }
}
